import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { wsManager } from '@/utils/websocket'
import { mockWebSocketService } from '@/utils/mockWebSocket'

export const useWebSocketStore = defineStore('websocket', () => {
  // 状态
  const isConnected = ref(false)
  const connectionStatus = ref<'disconnected' | 'connecting' | 'connected' | 'error'>('disconnected')
  const lastMessage = ref<any>(null)
  const messageHistory = ref<any[]>([])

  // 计算属性
  const canSend = computed(() => isConnected.value)

  // 操作
  const connect = async () => {
    try {
      connectionStatus.value = 'connecting'
      
      // 在开发环境使用模拟WebSocket服务
      if (import.meta.env.DEV) {
        mockWebSocketService.start()
        isConnected.value = true
        connectionStatus.value = 'connected'
        console.log('使用模拟WebSocket服务')
      } else {
        await wsManager.connect()
        isConnected.value = true
        connectionStatus.value = 'connected'
      }
    } catch (error) {
      connectionStatus.value = 'error'
      console.error('WebSocket连接失败:', error)
    }
  }

  const disconnect = () => {
    if (import.meta.env.DEV) {
      mockWebSocketService.stop()
    } else {
      wsManager.disconnect()
    }
    isConnected.value = false
    connectionStatus.value = 'disconnected'
  }

  const sendMessage = (type: string, data: any) => {
    if (canSend.value) {
      if (import.meta.env.DEV) {
        console.log('模拟发送消息:', { type, data })
        return true
      } else {
        return wsManager.send(type, data)
      }
    }
    return false
  }

  const subscribe = (type: string, callback: (data: any) => void) => {
    const wrappedCallback = (data: unknown) => {
      lastMessage.value = { type, data, timestamp: Date.now() }
      messageHistory.value.push(lastMessage.value)
      
      // 保持历史记录在合理范围内
      if (messageHistory.value.length > 100) {
        messageHistory.value = messageHistory.value.slice(-50)
      }
      
      callback(data)
    }

    if (import.meta.env.DEV) {
      return mockWebSocketService.subscribe(type, wrappedCallback)
    } else {
      return wsManager.subscribe(type, wrappedCallback)
    }
  }

  // 初始化
  const init = () => {
    // 监听WebSocket状态变化
    const checkConnection = () => {
      isConnected.value = wsManager.isConnected
    }
    
    setInterval(checkConnection, 1000)
  }

  return {
    isConnected,
    connectionStatus,
    lastMessage,
    messageHistory,
    canSend,
    connect,
    disconnect,
    sendMessage,
    subscribe,
    init,
  }
})